let Tesseract = require('tesseract.js')
const { createWorker, createScheduler } = require('tesseract.js')

const sharp = require('sharp');


async function preprocessImage(imagePath) {
    return new Promise((resolve, reject) => {
        sharp(imagePath)
            .grayscale() // 转换为灰度图像
            .threshold(128) // 二值化处理
            .toBuffer((err, buffer, info) => {
                resolve(buffer)
            }); // 保存处理后的图像

        //  toBuffer(callback: (err: Error, buffer: Buffer, info: OutputInfo) => void): Sharp;

        // console.log('图像已处理并保存为: ' + outputPath);
    })
}

let worker
let fun = async () => {
    worker = await createWorker('eng')
    await worker.setParameters({
        tessedit_char_whitelist: '0123456789.,()０１２３４５６７８９．，（）',
    });
}
fun()
let worker2
let arr = [
    '建邺城', '傲来国', '宝象国', '大唐境外',
    '女儿村', '普陀山', '五庄观', '西梁女国',
    '长寿村', '朱紫国', '江南野外'
]
let arr2 = [
    '出逃在', '附近', '帮我捉回来', '第个',
    ':', '：', '去', '处抓']
let arr3 = [
    '诌鬼', '假鬼', '奸鬼', '捣大鬼',
    '冒失鬼', '挖渣鬼', '仔细鬼', '讨吃鬼',
    '地哩鬼', '叫街鬼', '偷尸鬼', '寒碜鬼',
    '倒塌鬼', '涎脸鬼', '滴料鬼', '发贱鬼',
    '急急鬼', '耍碗鬼', '低达鬼', '遭瘟鬼',
    '轻薄鬼', '浇虚鬼', '绵缠鬼', '黑眼鬼',
    '龌龊鬼', '温斯鬼', '不通鬼', '诓骗鬼',
    '急赖鬼', '心病鬼', '醉死鬼', '抠掐鬼',
    '伶俐鬼', '急突鬼', '丢谎鬼', '乜斜鬼',
    '撩桥鬼'
];
let arr4 = [
    '子时', '丑时', '寅时', '卯时',
    '辰时', '巳时', '午时', '未时',
    '申时', '酉时', '戌时', '亥时'
];
let arr5 = [
    "一刻", "二刻", "三刻", "四刻",
    "五刻", "六刻", "七刻", "八刻"]

let str = arr.join('') + arr2.join('') + arr3.join('') + arr4.join('') + arr5.join('')
let fun2 = async () => {
    worker2 = await createWorker('chi_sim')
    await worker2.setParameters({
        tessedit_char_whitelist: '0123456789.,()０１２３４５６７８９．，（）' + str,
    });
}
fun2()
let worker3
let fun3 = async () => {
    worker3 = await createWorker('chi_sim')
    // await worker3.setParameters({
    //tessedit_char_whitelist: '0123456789.,()０１２３４５６７８９．，（）' + str,
    // });
}
fun3()
// 服务器的入口文件
// 1.创建KOA的实例对象
const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')

app.use(
    bodyParser({
        formLimit: '10mb',
        jsonLimit: '10mb',
        textLimit: '10mb',
        xmlLimit: '10mb',
    })
)
// 开发
app.use(async (ctx, next) => {
    let body = ctx.request.body
    // 拼接完整 图片
    let img = 'data:image/png;base64,' + body.base64
    // 创建本地文件
    const buffer = Buffer.from(body.base64, 'base64');
    // 写入本地文件
    // await fs.writeFileSync(buffer, buffer);
    // 笔记本 .108:8888
    // 
    let workeraa
    if (body?.all) {
        workeraa = worker2 // 坐标 + 鬼名字
    } else if (body?.all2) {
        workeraa = worker3 // 所有中文
        let fun = async () => {
            console.log('1111');

            let res = await workeraa.recognize(buffer)
            let res2 = await workeraa.recognize(buffer)
            let res3 = await workeraa.recognize(buffer)
            let res4 = await workeraa.recognize(buffer)
            let res5 = await workeraa.recognize(buffer)
            if (res.data.text == res2.data.text && res.data.text == res3.data.text && res.data.text == res4.data.text && res.data.text == res5.data.text) {
                ctx.body = (res.data.text + '').replace(/\n/g, '') + '';
                return
            } else {
                await fun()
            }
        }
        await fun()
        return
    } else {
        workeraa = worker // 坐标
        console.log('坐标');
    }
    let buffer_hui = await preprocessImage(buffer) // 灰度 因为坐标底部有根线与字 几乎同色
    console.log('buffer_hui', buffer_hui)
    let fun2 = async () => {
        let res = await workeraa.recognize(buffer_hui)
        let res2 = await workeraa.recognize(buffer_hui)
        let res3 = await workeraa.recognize(buffer_hui)
        let res4 = await workeraa.recognize(buffer_hui)
        let res5 = await workeraa.recognize(buffer_hui)
        if (res.data.text == res2.data.text && res.data.text == res3.data.text && res.data.text == res4.data.text && res.data.text == res5.data.text) {
            ctx.body = (res.data.text + '').replace(/\n/g, '') + '';
            return
        } else {
            await fun2()
        }
    }
    await fun2()
})

// 测试
// app.use(async (ctx, next) => {
//     const startTime = performance.now()
//     let body = ctx.request.body
//     let img = 'data:image/png;base64,' + body.base64
//     let res = await worker.recognize(img)
//     ctx.body = res.data.text
//     const endTime = performance.now()
//     const duration = endTime - startTime
//     console.log(`请求耗时: ${duration.toFixed(2)} 毫秒`)
// })

// 2.绑定中间件
// 绑定第一层中间件
const respDurationMiddleware = require('./middleware/koa_response_duration')
app.use(respDurationMiddleware)
// 绑定第二层中间件
const respHeaderMiddleware = require('./middleware/koa_response_header')
app.use(respHeaderMiddleware)
// 绑定第三层中间件
const respDataMiddleware = require('./middleware/koa_response_data')
app.use(respDataMiddleware)
// 3.绑定端口号 8888
app.listen(8888)

const webSocketService = require('./service/web_socket_service')
// 开启服务端的监听 , 监听客户端的链接
// 当 某一个客户端链接成功之后 , 就会对这个客户端进行message事件的监听
webSocketService.listen()
